package com.ziq.zcamp.manager

import android.graphics.Bitmap
import android.widget.Toast
import com.blankj.utilcode.util.ImageUtils
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat
import com.tencent.mm.opensdk.modelmsg.*
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.order.OrderPayResult
import com.ziq.zcamp.wxapi.WXPayEntryActivity


class WXAccount private constructor(){
    companion object {
        const val APP_ID = "wxa89ad234f56a0770"
        const val APP_SECRET = "a12a94a5f31a457e8c53715df76a06c7"
        const val APP_USER_NAME = "gh_e49819c001cf"
        const val RECEIVE_PAGA_PATH = "/subpages/other/web-view/index?url="

        val instance = SingletonHolder.holder
    }

    private object SingletonHolder {
        val holder= WXAccount()
    }

    var api: IWXAPI = WXAPIFactory.createWXAPI(GlobalContextManager.appContext, APP_ID)

    fun isWxInstalled(): Boolean {
        return api.isWXAppInstalled
    }

    fun openWXApp(): Boolean {
        return api.openWXApp()
    }

    fun loginWithWeChat() {
        // 将该app注册到微信
        val wxregister = api.registerApp(APP_ID)

        // 发送oauth请求，请求微信是否同意登录
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"
        req.state = "wechat_sdk_demo_test"
        val wxresssq = api.sendReq(req)
        if (!wxresssq) {
            Toast.makeText(GlobalContextManager.appContext, GlobalContextManager.getString(R.string.login_goto_checkwx), Toast.LENGTH_SHORT).show()
        }
    }

    fun startWxMiniProgram(path :String){
        if (!isWxInstalled()){
            Toast.makeText(GlobalContextManager.appContext,"请先安装微信",Toast.LENGTH_SHORT).show()
            return
        }
        val api = WXAPIFactory.createWXAPI(GlobalContextManager.appContext, APP_ID)
        val req = WXLaunchMiniProgram.Req()
        req.userName = APP_USER_NAME
        req.path = path
        if(true){
            req.miniprogramType =  WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW
        }else{
            req.miniprogramType =  WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE
        }
        api.sendReq(req)
    }

    //小程序首页
    //
    //  路径 pages/community/index
    //
    //帖子详情
    //  路径 subpages/community/post-detail/index
    //  参数 id=帖子id&creatorId=帖子创建者id
    //
    //营地详情
    //  路径 subpages/camp/camp-detail/index
    //  参数 id=营地id

    fun shareMiniProgram(cover: Bitmap?, title:String, description:String = "", path:String){
        val miniProgramObj = WXMiniProgramObject()
        miniProgramObj.webpageUrl = "http://www.qq.com" // 兼容低版本的网页链接
        if(true){
            miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPROGRAM_TYPE_PREVIEW // 正式版:0，测试版:1，体验版:2
        } else {
            miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE // 正式版:0，测试版:1，体验版:2
        }

        miniProgramObj.userName = "gh_e49819c001cf" // 小程序原始id
        miniProgramObj.path = path //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
        val msg = WXMediaMessage(miniProgramObj)
        if(title.isNotEmpty()){
            msg.title = title // 小程序消息title
        }
        msg.description = description // 小程序消息desc


//        var targetWidth = cover.width
//        var targetHeight = cover.height
//        if(targetWidth > 200){
//            targetWidth = 200
//            targetHeight = (200.0 / cover.width * cover.height).toInt()
//        }
//        val tempBmp = ImageUtils.scale(cover, targetWidth, targetHeight,true)
//        IKLog.i(Constants.LOG_TAG,"shareMiniProgram tempBmp: ${tempBmp.width}x${tempBmp.height} ${tempBmp.byteCount}")

        val tempByteArray = ImageUtils.compressByQuality(cover, 100 * 1000L, false)
        msg.thumbData = tempByteArray // 小程序消息封面图片，小于128k

        val req = SendMessageToWX.Req()
        req.transaction = ""
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession // 目前只支持会话

        api.sendReq(req)
    }

    fun sharePicture(pic: Bitmap, scene:Int = SendMessageToWX.Req.WXSceneSession){
        val imgObj = WXImageObject(pic)
        val msg = WXMediaMessage()
        msg.mediaObject = imgObj

        //设置缩略图
        val tempByteArray = ImageUtils.compressByQuality(pic, 25 * 1000L, false)
        msg.thumbData = tempByteArray

        val req = SendMessageToWX.Req()
        req.transaction = "img"
        req.message = msg
        req.scene = scene
        api.sendReq(req)
    }


    fun payWithWeChat(
        order : OrderPayResult,
        onSuccess: ((Int, String) -> Unit)? = null,
        onFail: ((Int, String) -> Unit)? = null
    ): Unit {
        if (!isWxInstalled()) {
            Toast.makeText(GlobalContextManager.appContext, "你当前还未安装微信客户端", Toast.LENGTH_SHORT).show()
            return
        }

        WXPayEntryActivity.callback = WXPayEntryActivity.IWXPayCallback { code, msg ->
            //清理回调
            WXPayEntryActivity.callback = null
            //支付结果回调
            if (code == 0) {
                onSuccess?.invoke(code, msg)
            } else {
                onFail?.invoke(code, msg)
            }
        }
        //调起微信支付
        val payReq = PayReq()
        payReq.appId = WXAccount.APP_ID
        payReq.packageValue = order.package_value?:"Sign=WXPay"
        payReq.partnerId = order.partner_id
        payReq.prepayId = order.prepay_id
        payReq.nonceStr = order.nonce
        payReq.timeStamp = order.timestamp?.toString()
        payReq.sign = order.sign
        api.sendReq(payReq)
    }

    fun canUseCustomerService():Boolean{
        return api.isWXAppInstalled && api.wxAppSupportAPI >= Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT
    }

    //微信客服
    fun openCustomerService(){
        // 判断当前版本是否支持拉起客服会话
        if (api.wxAppSupportAPI >= Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
            val req = WXOpenCustomerServiceChat.Req()
            req.corpId = "ww86320ba6fd2512c9" // 企业ID
            req.url = "https://work.weixin.qq.com/kfid/kfc4df475815363945d" // 客服URL
            api.sendReq(req)
        }
    }

}